import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_one/class/appbase/BaseEmptyView.dart';
import '../m/NewsInfoModel.dart';
import '../m/NewsTypeModel.dart';
import '../vm/NewsPageViewModel.dart';
import 'cell/NewsPageViewCell.dart';
import 'cell/NewsPageViewInformationCell.dart';
import 'package:flutter_one/class/appbase/BaseView.dart';

/*资讯列表子页面*/
class NewsPageChildView<VM extends NewsPageViewModel, TM extends NewsTypeModel>
    extends StatefulWidget {
  final VM viewModel;
  final TM typeModel;

  const NewsPageChildView(
      {super.key, required this.viewModel, required this.typeModel});

  @override
  State<NewsPageChildView<VM, TM>> createState() =>
      _NewsPageChildViewState<VM, TM>();
}

class _NewsPageChildViewState<VM extends NewsPageViewModel,
        TM extends NewsTypeModel> extends State<NewsPageChildView<VM, TM>>
    with AutomaticKeepAliveClientMixin {
  late VM viewModel;
  late TM typeModel;

  //首页默认1
  late int _pageNum = 1;

  //是否存在数据
  late bool _isEmpty = false;

  //true 存在下一页
  late bool _hasNextPage = false;

  //列表数据
  late List<NewsInfoModel> _arrList = <NewsInfoModel>[];

  late EasyRefreshController _refreshController;

  @override
  void initState() {
    viewModel = widget.viewModel;
    typeModel = widget.typeModel;
    _refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );

    // TODO: implement initState
    super.initState();

    //加载数据
    loadListDataFor(false);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    // TODO: implement build

    //设置UI
    return EasyRefresh.builder(
      controller: _refreshController,
      onRefresh: () async {
        //下拉刷新
        loadListDataFor(false);
      },
      onLoad: () async {
        //上拉加载更多
        loadListDataFor(true);
      },
      childBuilder: (BuildContext context, ScrollPhysics physics) {
        //空视图
        if (_isEmpty) {
          return BaseEmptyView(
              orignalEmptyType: EmptyViewType.no_order,
              tapAction: () {
                loadListDataFor(false);
              });
        }

        //加载
        if (_arrList.isEmpty) {
          return BaseView.loadingWidget();
        }

        return SafeArea(
          top: false,
          bottom: false,
          minimum: EdgeInsets.zero,
          maintainBottomViewPadding: true,
          child: _listView(physics),
        );
      },
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    debugPrint('$runtimeType 已销毁');
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

//MARK: 扩展
extension on _NewsPageChildViewState {
  //列表
  Widget _listView(ScrollPhysics? physics) {
    return CustomScrollView(
      physics: physics,
      primary: true,
      slivers: [
        SliverOverlapInjector(
          handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
        ),
        SliverPadding(
            padding: EdgeInsets.zero,
            sliver: SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  final m = _arrList[index];

                  if (m.className == '快讯') {
                    //7x24快讯
                    return NewsPageViewInformationCell(
                        index, m, context, viewModel);
                  }

                  return NewsPageViewCell(index, m, context, viewModel);
                },
                childCount: _arrList.length,
              ),
            )),
      ],
    );
  }

  // 加载对应列表数据
  void loadListDataFor(bool isLoadMore) {
    if (isLoadMore) {
      _pageNum += 1;
    } else {
      _pageNum = 1;
    }

    final int classId = typeModel.id;
    viewModel.listLoad(context, classId, _pageNum, finishBack:
        (bool isOk, String msg, List<NewsInfoModel>? arrList, int size) {
      //更新状态
      if (!isLoadMore) {
        //更新状态
        if (arrList?.isNotEmpty == true) {
          _refreshController.finishLoad(IndicatorResult.noMore);
        } else {
          _refreshController.finishRefresh();
        }
      } else {
        if (_hasNextPage) {
          _refreshController.resetFooter();
        } else {
          _refreshController.finishLoad(IndicatorResult.noMore);
        }
      }

      if (isOk) {
        setState(() {
          //更新数据
          if (arrList == null) {
            _arrList.clear();
            _isEmpty = true;
            _hasNextPage = false;
          } else {
            _isEmpty = false;
            _hasNextPage = arrList.length >= size;
            if (isLoadMore) {
              _arrList += arrList;
            } else {
              _arrList.clear();
              _arrList = arrList;
            }
          }
        });

        debugPrint(
            '加载成功!{${typeModel.name},${typeModel.id},${arrList?.length}}');
      } else {
        setState(() {
          _isEmpty = true;
          _hasNextPage = false;
        });

        debugPrint(msg);
      }
    });
  }
}
